<template>
  <div class="smart-import-page">
    <!-- 步骤指示器 -->
    <el-steps :active="currentStep" align-center style="margin-bottom: 24px">
      <el-step title="粘贴数据" description="输入客户信息" />
      <el-step title="AI 解析" description="智能提取字段" />
      <el-step title="审核确认" description="检查并编辑" />
      <el-step title="导入完成" description="数据入库" />
    </el-steps>

    <!-- 步骤 1: 粘贴数据 -->
    <el-card v-if="currentStep === 0">
      <template #header>
        <h2>⚡ 一键智能导入 - 客户数据资产化</h2>
      </template>

      <!-- 场景选择提示 -->
      <el-alert
        :type="detectedScenario === 'complex' ? 'warning' : 'success'"
        :closable="false"
        style="margin-bottom: 16px"
      >
        <template #title>
          <strong>{{ scenarioInfo.title }}</strong>
        </template>
        <div>{{ scenarioInfo.description }}</div>
        <div style="margin-top: 8px; font-size: 12px; color: #909399">
          {{ scenarioInfo.details }}
        </div>
      </el-alert>

      <el-input
        v-model="pasteText"
        type="textarea"
        :rows="12"
        maxlength="10000"
        show-word-limit
        placeholder="请粘贴客户信息（每行一个客户，最多100条）&#10;&#10;单客户场景示例（推荐）：&#10;张三,13812345678,整租,7000-8000,望京附近,近地铁&#10;李四，138...，想租整租，预算7000-8000，望京或国贸，要近地铁。也考虑合租3000-4000。&#10;&#10;多客户复杂场景示例：&#10;客户1: 张三,13812345678,整租,7000-8000,望京...&#10;客户2: 李四,13987654321,合租,3000-4000,国贸...&#10;&#10;💡 单条文本最多1000字符，AI会自动识别格式"
        @input="detectComplexity"
      />

      <div style="margin-top: 16px">
        <el-alert
          v-if="inputLines.length > 100"
          type="warning"
          :closable="false"
        >
          ⚠️ 检测到 {{ inputLines.length }} 条数据，建议单次不超过100条
        </el-alert>

        <el-alert
          v-if="pasteText.length > 5000"
          type="info"
          :closable="false"
          style="margin-top: 8px"
        >
          💡 内容较长，建议拆分为多段以提高AI识别准确率
        </el-alert>

        <!-- 复杂场景专属警告 -->
        <el-alert
          v-if="detectedScenario === 'complex'"
          type="warning"
          :closable="false"
          style="margin-top: 8px"
        >
          <template #title>
            <strong>⚠️ 复杂场景提醒</strong>
          </template>
          <div>
            • 检测到多客户或长文本，请仔细检查解析结果<br>
            • 预计处理时间：5-15秒
          </div>
        </el-alert>

        <!-- 简单场景提示 -->
        <el-alert
          v-if="detectedScenario === 'simple' && pasteText.trim()"
          type="success"
          :closable="false"
          style="margin-top: 8px"
        >
          <template #title>
            <strong>✓ 单客户场景</strong>
          </template>
          <div>
            • 快速处理，高准确率<br>
            • 预计处理时间：3-8秒
          </div>
        </el-alert>
      </div>

      <div style="margin-top: 24px; text-align: right">
        <el-button
          type="primary"
          size="large"
          :disabled="!pasteText.trim()"
          :loading="parsing"
          @click="handleParse"
        >
          <span v-if="detectedScenario === 'simple'">⚡ 快速解析（{{ inputLines.length }} 条）</span>
          <span v-else>🔍 深度解析（{{ inputLines.length }} 条，耗时较长）</span>
        </el-button>
      </div>
    </el-card>

    <!-- 步骤 2: AI 解析中 -->
    <el-card v-if="currentStep === 1">
      <el-result icon="info">
        <template #title>
          🤖 AI 正在处理...
        </template>
        <template #sub-title>
          总数: {{ totalCount }} 条
          <br>
          预计时间: {{ estimatedTime }}秒
        </template>
        <template #extra>
          <el-progress
            :percentage="progress"
            :stroke-width="20"
          />
        </template>
      </el-result>
    </el-card>

    <!-- 步骤 3: 审核工作台 -->
    <el-card v-if="currentStep === 2">
      <template #header>
        <div class="workbench-header">
          <h2>📋 审核工作台</h2>
          <el-space>
            <el-tag type="success">✓ 成功 {{ successCount }}</el-tag>
            <el-tag type="warning">⚠️ 需确认 {{ needsReviewCount }}</el-tag>
            <el-tag type="danger">✗ 失败 {{ failedCount }}</el-tag>
          </el-space>
        </div>
      </template>

      <!-- 批量操作栏 -->
      <div class="batch-actions">
        <el-checkbox
          v-model="selectAll"
          @change="handleSelectAll"
        >
          全选
        </el-checkbox>
        <el-button
          :disabled="selectedIndices.length === 0"
          @click="handleBatchDelete"
        >
          删除选中 ({{ selectedIndices.length }})
        </el-button>
        <el-button
          type="primary"
          :disabled="selectedValidItems.length === 0"
          :loading="importing"
          @click="handleConfirmImport"
        >
          ✅ 确认导入 ({{ selectedValidItems.length }} 条)
        </el-button>
      </div>

      <!-- 审核列表 -->
      <div class="review-list">
        <el-card
          v-for="(item, index) in parsedItems"
          :key="index"
          shadow="hover"
          style="margin-bottom: 16px"
          :class="{ 'selected-card': selectedIndices.includes(index) }"
        >
          <!-- 选择框和状态 -->
          <div class="card-header">
            <el-checkbox
              :model-value="selectedIndices.includes(index)"
              @change="(val) => handleSelectItem(index, val)"
            />
            <el-tag
              v-if="item.confidence > 0.9"
              type="success"
              size="small"
            >
              ✓ 置信度 {{ (item.confidence * 100).toFixed(0) }}%
            </el-tag>
            <el-tag
              v-else-if="item.confidence > 0.7"
              type="warning"
              size="small"
            >
              ⚠️ 置信度 {{ (item.confidence * 100).toFixed(0) }}%
            </el-tag>
            <el-tag
              v-else
              type="danger"
              size="small"
            >
              ✗ 置信度低
            </el-tag>
            <el-button
              type="primary"
              link
              size="small"
              @click="showConfidenceBreakdown(item)"
            >
              查看分析
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDeleteItem(index)"
            >
              删除
            </el-button>
          </div>

          <!-- 主意向（必填） -->
          <h4 style="margin-top: 16px">✅ 主意向（必填）</h4>
          <el-form label-width="100px">
            <el-row :gutter="16">
              <el-col :span="6">
                <el-form-item label="姓名">
                  <el-input v-model="item.lead.name" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机号">
                  <el-input v-model="item.lead.phone" size="small" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="需求类型">
                  <el-select v-model="item.lead.demand_type" size="small">
                    <el-option label="整租" value="rent_whole" />
                    <el-option label="合租" value="rent_shared" />
                    <el-option label="短租" value="rent_short" />
                    <el-option label="买房" value="buy" />
                    <el-option label="卖房" value="sell" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预算范围">
                  <el-input v-model="item.lead.budget_range" size="small" placeholder="7000-8000" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="标签">
                  <el-input v-model="item.lead.tag_names" size="small" placeholder="近地铁,安静" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input v-model="item.lead.notes" size="small" type="textarea" :rows="1" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 额外意向（可选） -->
          <div v-if="item.additional_intentions && item.additional_intentions.length > 0">
            <el-divider />
            <div style="display: flex; align-items: center; justify-content: space-between">
              <h4>📋 额外意向（{{ item.additional_intentions.length }}个）</h4>
              <el-dropdown trigger="click">
                <el-tag size="small" type="warning" style="cursor: pointer">
                  可选 ▼
                </el-tag>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item disabled>
                      <span style="color: #909399; font-size: 12px">
                        💡 额外意向管理（待设计）
                      </span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <el-table
              :data="item.additional_intentions"
              border
              size="small"
              style="margin-top: 8px"
            >
              <el-table-column label="需求类型" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.demand_type" size="small">
                    <el-option label="整租" value="rent_whole" />
                    <el-option label="合租" value="rent_shared" />
                    <el-option label="短租" value="rent_short" />
                    <el-option label="买房" value="buy" />
                    <el-option label="卖房" value="sell" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="预算下限" width="120">
                <template #default="{ row }">
                  <el-input-number v-model="row.budget_min" size="small" :controls="false" />
                </template>
              </el-table-column>
              <el-table-column label="预算上限" width="120">
                <template #default="{ row }">
                  <el-input-number v-model="row.budget_max" size="small" :controls="false" />
                </template>
              </el-table-column>
              <el-table-column label="区域" width="150">
                <template #default="{ row }">
                  <el-input
                    :model-value="formatAreaPreferences(row.area_preferences)"
                    @update:model-value="(val) => row.area_preferences = val"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="户型" width="100">
                <template #default="{ row }">
                  <el-input v-model="row.layout" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="意向度" width="100">
                <template #default="{ row }">
                  <el-select v-model="row.intention_level" size="small">
                    <el-option label="高" value="high" />
                    <el-option label="中" value="medium" />
                    <el-option label="低" value="low" />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>

            <el-alert type="info" style="margin-top: 8px" :closable="false">
              💡 额外意向是可选的，可以全部删除或部分保留
            </el-alert>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 步骤 4: 导入完成 -->
    <el-card v-if="currentStep === 3">
      <el-result
        icon="success"
        title="🎉 导入成功"
        :sub-title="`成功导入 ${importResult.created_leads} 个客户，${importResult.created_intentions} 个额外意向到企业数据资产库`"
      >
        <template #extra>
          <el-button type="primary" @click="$router.push('/leads')">
            查看客户列表
          </el-button>
          <el-button @click="reset">
            继续导入
          </el-button>
        </template>
      </el-result>
    </el-card>

    <!-- 置信度分析弹窗 -->
    <el-dialog
      v-model="showBreakdownDialog"
      title="📊 置信度详细分析"
      width="700px"
    >
      <div v-if="currentBreakdown">
        <!-- 总分概览 -->
        <el-alert
          :type="currentBreakdown.final_confidence >= 0.9 ? 'success' : (currentBreakdown.final_confidence >= 0.7 ? 'warning' : 'error')"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <template #title>
            <strong style="font-size: 18px">
              总分：{{ currentBreakdown.total_score }} / 100
              （置信度：{{ (currentBreakdown.final_confidence * 100).toFixed(0) }}%）
            </strong>
          </template>
          <div style="margin-top: 8px">
            <span v-if="currentBreakdown.final_confidence >= 0.9">
              ✅ 高质量数据，建议直接导入
            </span>
            <span v-else-if="currentBreakdown.final_confidence >= 0.7">
              ⚠️ 中等质量数据，建议人工审核
            </span>
            <span v-else>
              ❌ 低质量数据，建议修改后重新提交
            </span>
          </div>
        </el-alert>

        <!-- 各维度得分 -->
        <h4 style="margin-bottom: 12px">📈 各维度得分</h4>
        <el-progress
          :percentage="(currentBreakdown.required_fields_score / 40 * 100)"
          :stroke-width="20"
          :text-inside="true"
          status="success"
          style="margin-bottom: 12px"
        >
          <template #default>
            <span>1. 必填字段完整性：{{ currentBreakdown.required_fields_score }} / 40</span>
          </template>
        </el-progress>

        <el-progress
          :percentage="(currentBreakdown.optional_fields_score / 30 * 100)"
          :stroke-width="20"
          :text-inside="true"
          status="warning"
          style="margin-bottom: 12px"
        >
          <template #default>
            <span>2. 可选字段完整性：{{ currentBreakdown.optional_fields_score }} / 30</span>
          </template>
        </el-progress>

        <el-progress
          :percentage="(currentBreakdown.validation_score / 20 * 100)"
          :stroke-width="20"
          :text-inside="true"
          color="#409EFF"
          style="margin-bottom: 12px"
        >
          <template #default>
            <span>3. 数据合理性验证：{{ currentBreakdown.validation_score }} / 20</span>
          </template>
        </el-progress>

        <el-progress
          :percentage="(currentBreakdown.ai_confidence_score / 10 * 100)"
          :stroke-width="20"
          :text-inside="true"
          color="#909399"
          style="margin-bottom: 20px"
        >
          <template #default>
            <span>4. AI自评置信度：{{ currentBreakdown.ai_confidence_score }} / 10</span>
          </template>
        </el-progress>

        <!-- 详细评分项 -->
        <h4 style="margin-bottom: 12px">📋 详细评分项</h4>
        <el-table :data="getScoreDetails(currentBreakdown.scores)" border style="width: 100%">
          <el-table-column prop="category" label="分类" width="120" />
          <el-table-column prop="item" label="评分项" width="140" />
          <el-table-column prop="score" label="得分" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.score === row.max ? 'success' : (row.score > 0 ? 'warning' : 'danger')">
                {{ row.score }} / {{ row.max }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="detail" label="详情" />
        </el-table>
      </div>

      <template #footer>
        <el-button type="primary" @click="showBreakdownDialog = false">
          知道了
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/api/request'

defineOptions({ name: 'SmartImport' })

// ========== 状态管理 ==========
const currentStep = ref(0)
const pasteText = ref('')
const parsing = ref(false)
const importing = ref(false)
const parsedItems = ref<any[]>([])
const selectedIndices = ref<number[]>([])
const selectAll = ref(false)
const importResult = ref<any>({})
const detectedScenario = ref<'simple' | 'complex'>('simple')

// 置信度分析弹窗
const showBreakdownDialog = ref(false)
const currentBreakdown = ref<any>(null)

// ========== 计算属性 ==========
const inputLines = computed(() => {
  if (!pasteText.value.trim()) return []
  return pasteText.value.split('\n').filter(line => line.trim().length > 0)
})

const totalCount = computed(() => inputLines.value.length)

const estimatedTime = computed(() => {
  if (detectedScenario.value === 'complex') {
    // 复杂场景：15-60秒
    const batches = Math.ceil(totalCount.value / 5)
    return Math.max(15, batches * 12)
  } else {
    // 简单场景：4-15秒
    const batches = Math.ceil(totalCount.value / 5)
    return Math.max(4, batches * 3)
  }
})

const progress = computed(() => {
  if (currentStep.value !== 1) return 0
  return 50 // 简化处理
})

const successCount = computed(() => {
  return parsedItems.value.filter(item => item.confidence > 0.9).length
})

const needsReviewCount = computed(() => {
  return parsedItems.value.filter(item => item.confidence >= 0.7 && item.confidence <= 0.9).length
})

const failedCount = computed(() => {
  return parsedItems.value.filter(item => item.confidence < 0.7).length
})

// 选中的有效项（置信度>0.7且被选中）
const selectedValidItems = computed(() => {
  return parsedItems.value
    .filter((item, index) => selectedIndices.value.includes(index) && item.confidence > 0.7)
})

const scenarioInfo = computed(() => {
  if (detectedScenario.value === 'complex') {
    return {
      title: '🔍 复杂场景模式',
      description: '检测到多客户或长文本，将使用深度AI解析',
      details: '适用于: 多个客户信息、大量意向房源、超过500字的复杂描述'
    }
  } else {
    return {
      title: '⚡ 快速模式',
      description: '单客户场景，使用快速AI解析',
      details: '适用于: 单个客户、5-10个意向房源、简洁清晰的描述'
    }
  }
})

// ========== 方法 ==========
function detectComplexity() {
  const text = pasteText.value

  // 检测多客户标识
  const multiCustomerPatterns = [
    /客户[1-9]/,          // 客户1, 客户2
    /第[一二三四五]个客户/,
    /(?:姓名|名字)[1-9]/
  ]

  for (const pattern of multiCustomerPatterns) {
    if (pattern.test(text)) {
      detectedScenario.value = 'complex'
      return
    }
  }

  // 长文本视为复杂
  if (text.length > 500) {
    detectedScenario.value = 'complex'
    return
  }

  // 默认简单场景
  detectedScenario.value = 'simple'
}

async function handleParse() {
  if (!pasteText.value.trim()) {
    ElMessage.warning('请输入客户信息')
    return
  }

  if (inputLines.value.length > 100) {
    const confirmed = await ElMessageBox.confirm(
      `检测到 ${inputLines.value.length} 条数据，建议单次不超过100条。是否继续？`,
      '提示'
    )
    if (!confirmed) return
  }

  parsing.value = true
  currentStep.value = 1

  try {
    const response = await request.post('/v1/smart-import/parse', {
      texts: inputLines.value
    })

    // 处理包装格式 {code, message, data}
    const data = (response as any).data || response

    // 验证响应数据
    if (!data || !data.items) {
      throw new Error('API返回数据格式错误')
    }

    parsedItems.value = data.items || []

    // 只有在有解析结果时才进入下一步
    if (parsedItems.value.length > 0) {
      currentStep.value = 2
      ElMessage.success(`解析完成：成功${data.success || 0}条，失败${data.failed || 0}条`)
    } else {
      currentStep.value = 0
      ElMessage.warning('未能解析出任何有效数据，请检查输入格式')
    }
  } catch (error: any) {
    console.error('解析失败', error)

    // 区分网络错误和API错误
    if (error.code === 'ERR_NETWORK' || error.message === 'Network Error') {
      ElMessage.error('⚠️ 无法连接到后端服务器，请确认后端已启动（默认端口8000）')
    } else {
      ElMessage.error(error.response?.data?.detail || error.message || 'AI解析失败')
    }

    // 发生错误时重置到初始状态
    currentStep.value = 0
    parsedItems.value = []
  } finally {
    parsing.value = false
  }
}

function handleSelectAll(val: boolean | string | number) {
  if (val) {
    selectedIndices.value = parsedItems.value.map((_, index) => index)
  } else {
    selectedIndices.value = []
  }
}

function handleSelectItem(index: number, val: boolean | string | number) {
  if (val) {
    selectedIndices.value.push(index)
  } else {
    selectedIndices.value = selectedIndices.value.filter(i => i !== index)
  }
}

function handleBatchDelete() {
  parsedItems.value = parsedItems.value.filter((_, index) => !selectedIndices.value.includes(index))
  selectedIndices.value = []
  selectAll.value = false
  ElMessage.success('已删除选中项')
}

function handleDeleteItem(index: number) {
  parsedItems.value.splice(index, 1)
  ElMessage.success('已删除')
}

async function handleConfirmImport() {
  if (selectedValidItems.value.length === 0) {
    ElMessage.warning('请先选择要导入的数据')
    return
  }

  const confirmed = await ElMessageBox.confirm(
    `确认导入 ${selectedValidItems.value.length} 条数据到数据库？`,
    '确认导入'
  )

  if (!confirmed) return

  importing.value = true

  try {
    const response = await request.post('/v1/smart-import/import', {
      items: selectedValidItems.value
    })

    // 处理包装格式 {code, message, data}
    const data = (response as any).data || response

    // 验证响应数据
    if (!data) {
      throw new Error('API返回数据格式错误')
    }

    importResult.value = data

    // 只有在导入成功时才进入完成步骤
    // 后端返回字段：created_leads, created_intentions, errors
    const successCount = data.created_leads || 0
    const intentionCount = data.created_intentions || 0

    if (successCount > 0) {
      currentStep.value = 3
      ElMessage.success(
        (response as any).message ||
        `导入成功：${successCount}个客户${intentionCount > 0 ? `，${intentionCount}个额外意向` : ''}`
      )
    } else {
      // 显示具体错误信息
      const errorMsg = data.errors && data.errors.length > 0
        ? `导入失败：${data.errors[0]}`
        : '未能成功导入任何数据'
      ElMessage.warning(errorMsg)
    }
  } catch (error: any) {
    console.error('导入失败', error)

    // 区分网络错误和API错误
    if (error.code === 'ERR_NETWORK' || error.message === 'Network Error') {
      ElMessage.error('⚠️ 无法连接到后端服务器，请确认后端已启动（默认端口8000）')
    } else {
      ElMessage.error(error.response?.data?.detail || error.message || '导入失败')
    }

    // 发生错误时保持在审核确认步骤，不改变currentStep
  } finally {
    importing.value = false
  }
}

function showConfidenceBreakdown(item: any) {
  currentBreakdown.value = item.confidence_breakdown
  showBreakdownDialog.value = true
}

function formatAreaPreferences(value: string | null): string {
  if (!value) return ''

  // 如果已经是JSON字符串，解析它
  try {
    const parsed = JSON.parse(value)
    if (Array.isArray(parsed)) {
      return parsed.join(', ')
    }
    return value
  } catch {
    // 如果不是JSON，直接返回
    return value
  }
}

function getScoreDetails(scores: any) {
  if (!scores) return []

  const categoryMap: Record<string, string> = {
    name: '必填字段',
    phone_format: '必填字段',
    demand_type: '必填字段',
    budget_range: '可选字段',
    source_channel: '可选字段',
    tags: '可选字段',
    phone_validation: '合理性验证',
    budget_validation: '合理性验证',
    ai_confidence: 'AI自评'
  }

  const itemMap: Record<string, string> = {
    name: '姓名',
    phone_format: '手机号格式',
    demand_type: '需求类型',
    budget_range: '预算范围',
    source_channel: '来源渠道',
    tags: '标签',
    phone_validation: '手机号规则',
    budget_validation: '预算合理性',
    ai_confidence: 'AI置信度'
  }

  return Object.entries(scores).map(([key, data]: [string, any]) => ({
    category: categoryMap[key] || '其他',
    item: itemMap[key] || key,
    score: data.score,
    max: data.max,
    detail: data.message || data.value || '-'
  }))
}

function reset() {
  currentStep.value = 0
  pasteText.value = ''
  parsedItems.value = []
  selectedIndices.value = []
  importResult.value = {}
}
</script>

<style scoped>
.smart-import-page {
  padding: 24px;
}

.workbench-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.review-list {
  max-height: 600px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-card {
  border: 2px solid #409eff;
}
</style>
